import React, { useState, useEffect } from "react";
import { Table, Button, Select, Card, message } from "antd";
import { Bar } from "react-chartjs-2";
import { Chart as ChartJS, BarElement, CategoryScale, LinearScale, Tooltip, Legend } from "chart.js";
import axios from "axios";
import dayjs from "dayjs";

ChartJS.register(BarElement, CategoryScale, LinearScale, Tooltip, Legend);

const FortuneManagement = () => {
  const mockFortunes = [
    {
      id: "F001",
      username: "张伟_001",
      fortune_type: "八字测算",
      birth_year: 1990,
      birth_month: 5,
      birth_day: 12,
      birth_hour: "子时",
      created_at: "2024-03-10T14:32:00Z"
    },
    {
      id: "F002",
      username: "王芳_002",
      fortune_type: "紫微斗数",
      birth_year: 1988,
      birth_month: 11,
      birth_day: 23,
      birth_hour: "午时",
      created_at: "2024-03-12T09:15:00Z"
    },
    {
      id: "F003",
      username: "李娜_003",
      fortune_type: "手相分析",
      birth_year: 1995,
      birth_month: 2,
      birth_day: 14,
      birth_hour: "申时",
      created_at: "2024-03-11T18:45:00Z"
    },
    {
      id: "F004",
      username: "陈强_004",
      fortune_type: "塔罗牌阵",
      birth_year: 1985,
      birth_month: 8,
      birth_day: 8,
      birth_hour: "亥时",
      created_at: "2024-03-13T10:00:00Z"
    }
  ];
  
  const mockTypeDistribution = [
    { fortune_type: "八字测算", count: 45 },
    { fortune_type: "紫微斗数", count: 30 },
    { fortune_type: "手相分析", count: 25 },
    { fortune_type: "塔罗牌阵", count: 40 }
  ];
  const [fortunes, setFortunes] = useState(mockFortunes);
  const [loading, setLoading] = useState(false);
  const [fortuneType, setFortuneType] = useState("全部");
  const [typeDistribution, setTypeDistribution] = useState(mockTypeDistribution);

  const fetchFortunes = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/userfortune/getcsgl", {
        params: { fortune_type: fortuneType },
      });
      console.log(response.data.data,'response')
      setFortunes(response.data.data);
      setTypeDistribution( getFortuneTypeStats(response.data.data))
     
    } catch (error) {
      console.error("Error fetching fortunes:", error);
      message.error("获取测算记录失败");
    } finally {
      setLoading(false);
    }
  };
  const getFortuneTypeStats = (data) => {
    const typeCounter = {};
  
    // 遍历统计
    data.forEach(item => {
      const type = item.fortune_type;
      typeCounter[type] = (typeCounter[type] || 0) + 1;
    });
  
    // 格式转换
    return Object.entries(typeCounter).map(([type, count]) => ({
      fortune_type: type,
      count: count
    }));
  };
  // const fetchTypeDistribution = async () => {
  //   try {
  //     const response = await axios.get("http://localhost:5000/api/stats/fortunes");
  //     setTypeDistribution(response.data.typeDistribution);
  //   } catch (error) {
  //     console.error("Error fetching type distribution:", error);
  //   }
  // };

  useEffect(() => {
    fetchFortunes();
    // fetchTypeDistribution();
  }, [fortuneType]);

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5000/api/fortunes/${id}`);
      setFortunes(fortunes.filter((fortune) => fortune.id !== id));
      message.success("测算记录删除成功");
    } catch (error) {
      console.error("Error deleting fortune:", error);
      message.error("删除测算记录失败");
    }
  };

  const columns = [
    { title: "用户名", dataIndex: "username", key: "username" },
    { title: "测算类型", dataIndex: "fortune_type", key: "fortune_type" },
    // { title: "生辰", key: "birth", render: (_, record) => `${record.birth_year}-${record.birth_month}-${record.birth_day} ${record.birth_hour}` },
    { title: "创建时间", dataIndex: "created_at", key: "created_at", render: (text) => dayjs(text).format("YYYY-MM-DD HH:mm:ss") },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Button danger onClick={() => handleDelete(record.id)}>
          删除
        </Button>
      ),
    },
  ];

  const typeData = {
    labels: typeDistribution.map((item) => item.fortune_type),
    datasets: [
      {
        label: "测算次数",
        data: typeDistribution.map((item) => item.count),
        backgroundColor: "#FFCE56",
      },
    ],
  };

  return (
    <div style={{ padding: "24px" }}>
      <div style={{ marginBottom: "24px" }}>
        <Select
          value={fortuneType}
          onChange={setFortuneType}
          style={{ width: 200 }}
        >
          <Select.Option value="全部">全部</Select.Option>
          <Select.Option value="八字测算">八字测算</Select.Option>
          <Select.Option value="紫微斗数">紫微斗数</Select.Option>
        </Select>
      </div>
      <Table
        columns={columns}
        dataSource={fortunes}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
      <Card title="测算类型分布" style={{ marginTop: 24 }}>
        <Bar data={typeData} options={{ maintainAspectRatio: false }} height={250} />
      </Card>
    </div>
  );
};

export default FortuneManagement;